package net.sf.rose.business.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import net.sf.rose.business.bean.base.FileBean;
import net.sf.rose.business.bean.base.Group;
import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.jdbc.KeyGenerator;
import net.sf.rose.jdbc.GenericDAO;
import net.sf.rose.jdbc.QueryBeanSQL;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.jdbc.service.DataBaseFactory;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.DateUtil;

import org.apache.log4j.Logger;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/**
 * 功能：工作组服务类
 * <p>数据保存在数据库附件表中，键名是“group”，附件是XML格式
 * <p>数据直接解析为Group的实体类
 * @author fengjian
 * @since 2014/02/27
 */
public class GroupSevice {

	private static Logger logger = Logger.getLogger(GroupSevice.class);

	/** 工作组存储在数据库中的名称 */
	private static String NAME = "group_meta";

	/** 工作组存储在数据库中的分类名称 */
	private static String SORT = "config";

	/** 本类的单例 */
	private static GroupSevice service = null;

	/** 数据类的单例 */
	private static FileBean fileBean = null;

	static {
		Service s = DataBaseFactory.getService();
		UserBean user = new UserBean();
		user.setUserName("system");
		s.setUser(user);
		GenericDAO dao = new GenericDAO(s);
		QueryBeanSQL query = new QueryBeanSQL(s);
		fileBean = new FileBean();
		fileBean.setCode(NAME);
		fileBean.setFileSort(SORT);
		try {
			query.createListSql(fileBean);
			Object obj = dao.load(query);
			if (obj != null) {
				fileBean = (FileBean) obj;
				InputStream in = fileBean.getFile();
				if (in != null) {
					Serializer serializer = new Persister();
					service = serializer.read(GroupSevice.class, in);
				}
			}
			if (service == null) {
				service = new GroupSevice();
				Group group = new Group();
				group.setId("100");
				group.setCode("root");
				group.setText("根目录");
				service.setGroup(group);
			}
		} catch (SystemException e) {
			throw e;
		} catch (Exception e) {
			String message = "工作组初始化失败！";
			logger.error(message, e);
			throw new SystemException(message, SystemErrorCode.APPLICATION_ERROR);
		} finally {
			s.close();
		}
	}

	/**
	 * 
	 */
	public static void save(UserBean user) {
		Service s = DataBaseFactory.getService();
		GenericDAO dao = new GenericDAO(s);
		QueryBeanSQL query = new QueryBeanSQL(s);
		try {
			Serializer serializer = new Persister();
			File file = new File(System.getenv("TEMP"), KeyGenerator.getUID());
			serializer.write(service, file);
			InputStream in = new FileInputStream(file);
			fileBean.setFile(in);
			if (fileBean.getFileID() == null) {
				fileBean.setFileID(KeyGenerator.getUID());
				fileBean.setCreateUser(user.getUserName());
				fileBean.setCreateTime(DateUtil.getTimestamp());
				query.createInsertSql(fileBean);
			} else {
				fileBean.setUpdateUser(user.getUserName());
				fileBean.setUpdateTime(DateUtil.getTimestamp());
				query.createUpdateSql(fileBean);
			}
			dao.update(query);
			s.commit();
		} catch (SystemException e) {
			throw e;
		} catch (Exception e) {
			throw new SystemException("工作组保存失败！", SystemErrorCode.APPLICATION_ERROR);
		} finally {
			s.close();
		}
	}

	public static GroupSevice getService() {
		return service;
	}

	public static Group getRoot() {
		return service.group;
	}

	/** 页内属性的访问权限 */
	@Element
	private Group group = null;

	public Group getGroup() {
		return group;
	}

	public void setGroup(Group group) {
		this.group = group;
	}

	/**
	 * 功能:返回给出工作组的父工作组
	 * @param child - 当前工作组
	 * @return 父工作组
	 */
	public Group getParent(Group child) {
		String id = child.getId();
		if (id.length() < 7) {
			return service.group;
		}
		id = id.substring(0, id.length() - 3);
		int length = id.length() / 3;
		int count = 2;
		String sid = id.substring(0, count * 3);
		Group parent = group;
		do {
			for (Group p : parent.getChildGroup()) {
				if (p.getId().equals(sid)) {
					parent = p;
					break;
				}
			}
			if (count == length) {
				sid = null;
			} else {
				count++;
				sid = id.substring(0, count * 3);
			}
		} while (sid != null);
		return parent;
	}
	
	/**
	 * 功能:返回给出工作组的父工作组
	 * @param child - 当前工作组
	 * @return 父工作组
	 */
	public Group getGroup(String id) {
		if (id.length() == 3) {
			return service.group;
		}
		int length = id.length() / 3;
		int count = 2;
		String sid = null;
		Group parent = group;
		do {
			sid = id.substring(0, count * 3);
			for (Group p : parent.getChildGroup()) {
				if (p.getId().equals(sid)) {
					parent = p;
					break;
				}
			}
			if (count == length) {
				sid = null;
			} else {
				count++;
			}
		} while (sid != null);
		if (count == length) {
			return parent;
		} else {
			return null;
		}
	}
	
	public String getGroupTree() {
		StringBuilder sb = new StringBuilder();
		this.addGroup(sb, group);
		return sb.toString();
	}

	private void addGroup(StringBuilder sb, Group group) {
		sb.append("<li><a href=\"javascript:\" onclick=\"$.bringBack({id:'" +group.getId() + "',name:'" + group.getText() + "'});\" >").append(group.getText()).append("</a>");
		if (group.getChildGroup().size() > 0) {
			sb.append("<ul>");
			for (Group child : group.getChildGroup()) {
				this.addGroup(sb, child);
			}
			sb.append("</ul>");
		}
		sb.append("</li>");
	}
}
